<template>
  <el-dialog
    title="重命名目录"
    :visible="dialogVisible"
    append-to-body
    close-on-press-escape
    :close-on-click-modal="false"
    custom-class="custom-dialog"
    @open="initFolderTitle"
    @opened="inputFocus"
    @close="closeDialog"
    width="26rem"
  >
    <el-form ref="form" :model="form" :rules="rules">
      <el-form-item prop="title">
        <el-input
          ref="input"
          v-model.trim="form.title"
          placeholder="请输入目录名"
          @keyup.enter.native="onSubmit"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="flex content-space-between">
      <el-button
        type="primary"
        @click="onSubmit"
        :loading="loading"
        v-text="'保存'"
      />
      <el-button @click="closeDialog">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { formatFolder } from '@/components/spaces/resources-v2/format';

export default {
  name: 'rename-folder-dialog',
  props: {
    dialogVisible: Boolean,
    folder: Object,
    spaceId: {},
  },
  data() {
    return {
      form: { title: this.folder.title },
      rules: {
        title: [{ validator: this.$va.folderTitle, trigger: 'change' }],
      },
      loading: false,
    };
  },
  methods: {
    onSubmit() {
      this.loading = true;
      this.$api.spaceResources.renameFolder({
        spaceId: this.spaceId,
        folderId: this.folder.id,
        title: this.form.title,
      }).then((res) => {
        this.$message.success('重命名成功');
        this.$emit('renamedFolder', this.folder, formatFolder(res.data));
        this.closeDialog();
      }).catch(() => {})
        .then(() => { this.loading = false; });
    },
    initFolderTitle() { this.form.title = this.folder.title; },
    inputFocus() { this.$refs.input.focus(); },
    closeDialog() {
      this.$refs.form.resetFields();
      this.$emit('update:dialogVisible', false);
    },
  },
};
</script>

<style></style>
